package com.jack.helloworld.activity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.jack.helloworld.R;
import com.jack.helloworld.service.MusicService;

public class ServiceActivity extends AppCompatActivity {

    private ServiceConnection serviceConnection;
    private MusicService musicBinderService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sevice);
        
        initData();
    }

    private void initData() {
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Toast.makeText(ServiceActivity.this, "onServiceConnected", Toast.LENGTH_SHORT).show();
                musicBinderService = ((MusicService.MusicBinderService) service).getService();

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Toast.makeText(ServiceActivity.this, "onServiceDisconnected", Toast.LENGTH_SHORT).show();
            }
        };
    }


    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.btnBindService:
                Intent intent = new Intent(this, MusicService.class);
                bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);

                break;
            case R.id.btnUnBindService:
                if (serviceConnection != null) {
                    unbindService(serviceConnection);
                    serviceConnection = null;
                }
                break;
            case R.id.btnStart:
                musicBinderService.start();
                break;
            case R.id.btnPrevious:
                musicBinderService.previous();
                break;
            case R.id.btnNext:
                musicBinderService.next();
                break;
            case R.id.btnStop:
                musicBinderService.stop();
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (serviceConnection != null) {
            unbindService(serviceConnection);
            serviceConnection = null;
        }
    }
}
